import Vue from 'vue'
import Router from 'vue-router'
import routes from './staticRouter'
import store from './store'
Vue.use(Router)

const route = new Router({
  routes
})
let flag = true
route.beforeEach((to, from, next) => {
  let a = store.state.rout.router
  if (a.length != 0 && flag) {
    a.forEach(item => {
      item.component = getComponent(item.name)
      if(item.children){
        item.children = getChildren(item.children)
      }
      route.addRoute(item)
    })
    flag = false
    next({
      ...to,
      replace:true
    })
  }else{
    next()
  }
})

function getComponent(name) {
  return () => import(`./views/${name}`)
}

function getChildren(children){
  children.forEach(item=>{
    item.component = getComponent(item.name)
    if(item.children !=undefined){
      getChildren(item.children)
    }
  })
  return children
}



export default route
